<template>
	<view class="container">

		<!-- 地址块 -->
		<view class="areaContent" @tap="toSelectAddress()">
			<view class="iconContent">

			</view>
			<view class="areaInfo">
				<block v-if="existDefaultAddress">
					<view class="areaTitle">
						{{addressInfo.addressConsigneeProvinceName}}{{addressInfo.addressConsigneeCityName}}{{addressInfo.addressConsigneeDistrictName}}{{addressInfo.addressConsigneeDetail}}
					</view>
					<view class="personInfo">
						<text class="name">{{addressInfo.addressConsigneeName}} </text>
						<text class="phone">{{addressInfo.addressConsigneePhone}}</text>
					</view>
				</block>
				<block v-else>
					<view class="areaTitle">
						请填写收货地址
					</view>
					<view class="personInfo">
						点击填写
					</view>
				</block>
			</view>

			<view class="icon">
				<uni-icons type="forward" size="15"></uni-icons>
			</view>
		</view>



		<!-- 商品卡片 -->
		<view v-if="toBePurchaseList.length" class="cart-list">
			<view class="cart-item" v-for="(item, index) in toBePurchaseList" :key="index">
				<view class="goods-image">
					<image class="image" :src="item.productDetail.productDetailImg" mode="scaleToFill"></image>
				</view>
				<view class="item-content">
					<view class="goods-title">
						<text class="twoline-hide">{{ item.productName }}</text>
					</view>
					<view class="goods-props clearfix">
						<view class="goods-props-item">
							<text>{{item.productDetail.productDetailSpecifications}}</text>
						</view>
					</view>
					<view class="item-foot">
						<view class="goods-price">
							<text class="unit">￥</text>
							<text class="value">{{ Number(item.productDetail.productDetailPrice).toFixed(2)  }}</text>
						</view>
						<stepper :itemNum="item.shoppingCartQuantity" @add="num=>toAdd(num,item.productDetail.id)"
							@minus="num=>toMinus(num,item.productDetail.id)"
							@blur="num=>toBlur(num,item.productDetail.id)"></stepper>
					</view>
				</view>
			</view>
		</view>


		<!-- 运费与备注板块 -->
		<view class="deliverDetail">
			<view class="deliverPrice">
				<text>运费</text>
				<text class="price">￥{{Number(develiverFee).toFixed(2)}}</text>
			</view>

			<view class="remark">
				<text class="textContent">订单备注</text>

				<view class="remarkDisplay">

				</view>

				<view class="displayText">
					<input type="text" v-model="remark" placeholder="无备注">
					<uni-icons type="forward" size="15" style="text-align: center;"></uni-icons>
				</view>





			</view>
		</view>

		<!-- 支付板块 -->
		<view class="pay">
			<view class="title">
				<view class="iconContent">

				</view>
				<text>微信支付</text>
			</view>

			<view class="selectPay">
				<uni-icons type="checkbox-filled" size="30" color="rgba(223, 161, 60, 1);"
					style="text-align: center; "></uni-icons>
			</view>

		</view>



		<!-- 订单提交板块 -->
		<view class="confirmFooter">
			<view class="confirmContent">
				<view class="textContent">
					<text>合计</text>
					<text class="price">￥{{Number(totalPriceConfirm+develiverFee).toFixed(2)}}</text>
				</view>
				<button class="submit" type="submit" @click="confirm()">提交订单</button>
			</view>
		</view>


		<!-- 兜底用到的提示卡片 -->
		<view class="mask" v-if="isShow"></view>
		<errHintCard :isShowHint="isShow" @closeHint="closeHint()"></errHintCard>
	</view>
</template>

<script>
	// 导入测试数据
	import stepper from '@/components/stepper.vue'
	import * as ordersApi from '@/api/orders/orders.js'
	import * as AddressApi from '@/api/address/address.js'
	import * as ProductApi from '@/api/product/product.js'
	import * as payApi from '@/api/pay/pay.js'
	import errHintCard from '@/components/goodsChangeHintCard/goodsChangeHintCard.vue'
	let lastRequestTime = 0;
	const requestInterval = 1000; // 设置请求的最小间隔时间，例如1000毫秒
	export default {
		components: {
			stepper,
			errHintCard
		},
		data() {
			return {
				// 兜底支付的提示卡片
				isShow: false,
				infoStatus: true,
				addressInfo: null,
				//初始化地址列表
				addressList: null,
				//将要购买的商品列表,用来渲染
				existDefaultAddress: false,
				toBePurchaseList: [],
				//如果用户选择了地址那么回传地址Id,重新渲染订单信息,
				// 用来对选择的数组进行操作
				ordersDetailSimpleList: null,
				// 商品总价
				totalPriceConfirm: 0,


				addressId: null,

				changeAddressId: null,
				remark: '',


				// 生成订单后后台传回的需要唤起微信支付的数据

			}
		},
		computed: {

			totalQuantity() {
				return this.toBePurchaseList.reduce((total, item) => {
					return Number(total) + ( Number(item.shoppingCartQuantity)|| 0);
				}, 0);

			},


			develiverFee() {
					
				
				if (this.totalQuantity <= 2) {
					return 8; // 1-2盒的运费为8元
				} else if (this.totalQuantity <= 4) {
					return 15; // 3-4盒的运费为15元
				} else if (this.totalQuantity <= 6) {
					return 20; // 5-6盒的运费为20元
				} else {
					return 3 * this.totalQuantity; // 6盒以上的情况：3元*盒数
				}
			}
		},
		onLoad(options) {
			const paramsStr = options.params || null; // 获取URL查询参数中的params字段
			//接收个人中心传来的订单类型
			if (paramsStr != null) {
				const receivedParams = JSON.parse(paramsStr);
				this.toBePurchaseList = receivedParams.toBePurchaseList;
				this.getSelectedTotalPrice()
				this.addressInit();
			}
		},
		onShow() {
			this.addressInit();

		},
		methods: {
			//兜底关闭弹窗并退出
			closeHint() {
				this.isShow = false;
				uni.$toPage('/pages/cart/cart')
			},
			async addressInit() {
				const res = await AddressApi.getAddressList();
				console.log("地址列表")
				console.log(res)
				this.addressList = res.data.data;
				//地址表里总是会有一个默认地址我们只需要判断地址列表是否为空就行了
				if (this.addressList != null || this.addressList.length != 0) {
					if (this.$globalData.commonDeleteFlag === true) {
						this.$globalData.selectedCommonAddress = null;
						this.$globalData.commonDeleteFlag = null;
					}

					if (this.$globalData.selectedCommonAddress === null) {
						this.addressInfo = this.addressList.find(item => item.addressWxuserDefault == 1);
						

					} else {
						this.addressInfo = this.addressList.find(item => item.id === this.$globalData
							.selectedCommonAddress)

					}

					this.addressId = this.addressInfo.id;
					this.existDefaultAddress = true;
				}
			},
			//根据点击购买传来的商品数量和子商品ID，获取信息


			// 跳转地址修改
			toSelectAddress() {
				const currentTime = new Date().getTime();
				if (currentTime - lastRequestTime < requestInterval) {
					return uni.$showMsg('操作过于频繁'); // 这将阻止请求继续执行
				}
				lastRequestTime = currentTime; // 更新上一次请求时间
				uni.$toPage('/subpkg/shoppingMall/addressList/addressList', {
					isChooseStatus: true
				})
			},


			//计算商品总价
			getSelectedTotalPrice() {
				this.totalPriceConfirm = this.toBePurchaseList.reduce((total, item) => {
					// 计算每个子商品的价格，productDetailPrice * quantity
					const itemTotal = item.productDetail.productDetailPrice * item.shoppingCartQuantity;
					// 累加到总和上
					return total + itemTotal;
				}, 0); // 初始总和为 0
			},
			//对商品数量进行调整的方法
			toAdd(num, id) {
				this.toBePurchaseList.forEach(item => {
					if (item.productDetail.id === id) {
						console.log("找到了")
						console.log(item)
						item.shoppingCartQuantity = num;
					}
				});
				this.getSelectedTotalPrice()

			},
			toMinus(num, id) {
				console.log("减少商品数量的方法")
				this.toBePurchaseList.forEach(item => {
					if (item.productDetail.id === id) {
						console.log("找到了")
						console.log(item)
						item.shoppingCartQuantity = num;
					}
				});
				this.getSelectedTotalPrice()
			},

			toBlur(num, id) {
				console.log("输入商品数量后触发的方法")
				this.toBePurchaseList.forEach(item => {
					if (item.productDetail.id === id) {
						console.log("找到了")
						console.log(item)
						item.shoppingCartQuantity = num;
					}
				});
				this.getSelectedTotalPrice()

			},

			// 提交订单结算界面
			async confirm() {
				if (this.existDefaultAddress === false) {
					return uni.$showMsg('请先选择地址')
				}
				if (this.toBePurchaseList.length === 0) {
					return uni.$showMsg('操作过快')
				}
				const currentTime = new Date().getTime();
				if (currentTime - lastRequestTime < requestInterval) {
					return uni.$showMsg('操作过于频繁'); // 这将阻止请求继续执行
				}
				lastRequestTime = currentTime; // 更新上一次请求时间
				
				
				// 初始化 payInfoList
				let payInfoList = [];

				// 遍历 this.toBePurchaseList 并提取所需数据
				this.toBePurchaseList.forEach(item => {
					// 创建新对象并赋值
					let newObject = {
						productDetailId: item.productDetail.id,
						ordersDetailNumber: item.shoppingCartQuantity,
						productDetailPrice: Number(item.productDetail.productDetailPrice).toFixed(2),
						productName: item.productName,
						productDetailSpecifications: item.productDetail.productDetailSpecifications

					};

					// 将新对象推入 payInfoList
					payInfoList.push(newObject);
				});

				const generateOrders = {
					jumpPage: 2,
					addressBookId: this.addressId,
					ordersThingAmount: Number(this.totalPriceConfirm).toFixed(2),
					ordersTransportAmount: Number(this.develiverFee).toFixed(2),
					ordersDetailSimpleList: payInfoList,
					ordersRemark: this.remark
				}

				//生成订单从后台拿支付数据
				const res = await ordersApi.addOrder(generateOrders);
				console.log("订单号")
				console.log(res)
				if (res.data.code === 200) {
					const orderId = res.data.data;
					const payRes = await payApi.payOrderMoney(orderId)
					console.log(payRes)
					if (payRes.data.code === 200) {
						let orderResponseData = payRes.data.data.stringStringMap;
						uni.$WxPay(orderResponseData)
							.then(response => {
								// 支付成功的处理
								uni.$toPage(
									'/subpkg/shoppingMall/orderConfirmTransferPage/orderConfirmTransferPage', {},
									false, false, true)
							})
							.catch(error => {
								// 支付失败的处理
								uni.$showMsg('取消支付')

								uni.$toPage('/subpkg/shoppingMall/order_list/order_list', {
									orderType: 1
								}, false, false, true)
							});
					}
				} else if (res.data.code === 320 || res.data.code === 321) {
					this.isShow = true;

				}






			},


		}
	}
</script>

<style scoped lang="scss">
	page {
		background-color: rgba(235, 236, 237, 1);
	}

	.container {
		.mask {
			background: rgba(0, 0, 0, 0.25);
			width: 100vw;
			height: 100vh;
			position: absolute;
		}

		width: 100%;
		padding-bottom: 300rpx;
		overflow: scroll;
		display: flex;
		flex-wrap: wrap;
		flex-direction: column;
		align-items: center;
		box-sizing: border-box;

		// 地址板块
		.areaContent {


			margin-top: 30rpx;
			box-sizing: border-box;
			background-color: rgba(255, 255, 255, 1);
			width: 694rpx;
			position: relative;
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
			border-radius: 14rpx;
			background: rgba(255, 255, 255, 1);
			margin-bottom: 28rpx;
			box-sizing: border-box;

			.iconContent {
				margin-left: 24rpx;
				width: 32rpx;
				height: 32rpx;
				box-sizing: border-box;
				background: url('https://zhinengjiayi.oss-cn-chengdu.aliyuncs.com/service/spcar_icon_address_default%404x.png');
				background-size: cover;
			}

			.areaInfo {
				margin-top: 20rpx;
				margin-bottom: 20rpx;
				padding-top: 0rpx;
				box-sizing: border-box;

				.areaTitle {
					margin-top: 0rpx;
					width: 504rpx;
					overflow: hidden;
					text-overflow: ellipsis;
				}

				.personInfo {
					box-sizing: border-box;
					margin-top: 16rpx;
					width: 231rpx;
					font-size: 24rpx;
					color: rgba(56, 56, 56, 1);
					white-space: nowrap;

					.name {
						margin-right: 5rpx;
					}

				}
			}

			.icon {

				padding-right: 28rpx;
			}
		}

		// 商品卡片
		.cart-list {
			width: 694rpx;

			box-sizing: border-box;

			.cart-item {
				box-sizing: border-box;
				background: #fff;
				border-radius: 12rpx;
				display: flex;
				align-items: center;
				padding: 30rpx 16rpx;
				margin-bottom: 24rpx;
				border-radius: 5%;
				height: 178rpx;

				.goods-image {
					width: 158rpx;
					height: 158rpx;

					.image {
						display: block;
						width: 100%;
						height: 100%;
						border-radius: 8rpx;
					}
				}

				.item-content {
					flex: 1;
					padding-left: 24rpx;

					.goods-title {
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
						width: 422rpx;
						font-size: 28rpx;
						max-height: 76rpx;
					}

					.goods-props {
						padding-left: 0;
						text-align: left;

						margin-top: 14rpx;
						height: 40rpx;
						color: #ababab;
						font-size: 24rpx;
						overflow: hidden;

						.goods-props-item {
							display: inline-block;
							margin-right: 14rpx;
							padding: 4rpx 16rpx;
							border-radius: 12rpx;
							width: auto;
						}
					}


					.item-foot {
						display: flex;
						justify-content: space-between;
						align-items: center;
						margin-top: 20rpx;
						position: relative;


						.goods-price {
							vertical-align: bottom;
							font-size: 36rpx;
							font-weight: 700;
							color: rgba(212, 48, 48, 1);

							.unit {
								font-size: 24rpx;
							}

							.value {
								font-size: 32rpx;
							}
						}





					}

				}
			}

		}


		// 配送细节
		.deliverDetail {
			background-color: rgba(255, 255, 255, 1);
			width: 692rpx;
			height: 166rpx;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			align-items: center;
			border-radius: 14rpx;
			background: rgba(255, 255, 255, 1);
			margin-bottom: 30rpx;

			.deliverPrice {
				width: 632rpx;
				height: 83rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;


			}


			.remark {
				width: 632rpx;
				height: 83rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.textContent {
					white-space: nowrap;
					padding-right: 15rpx;

				}

				.displayText {
					display: flex;
					align-items: center;
					color: rgba(166, 166, 166, 1);

					input {
						text-align: right;
						text-overflow: ellipsis;
					}
				}


			}


		}

		// 支付板块
		.pay {
			box-sizing: border-box;
			background-color: rgba(255, 255, 255, 1);
			width: 692rpx;
			height: 104rpx;
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
			border-radius: 14rpx;

			.title {

				display: flex;
				align-items: center;
				justify-content: center;
				padding-left: 30rpx;

				text {
					margin-left: 20rpx;
				}

				.iconContent {
					box-sizing: border-box;
					width: 44rpx;
					height: 38rpx;
					background: url('https://zhinengjiayi.oss-cn-chengdu.aliyuncs.com/service/spcar_icon_WeChat%20pay_default%404x.png');
					background-size: cover;

				}
			}

			.selectPay {
				padding-right: 30rpx;
			}

		}

		//订单提交板块
		.confirmFooter {
			z-index: 9999999999;
			box-sizing: border-box;
			display: flex;
			width: 100%;
			height: 190rpx;
			position: fixed;
			bottom: 0;
			background: rgba(255, 255, 255, 1);

			.confirmContent {
				padding-left: 54rpx;
				width: 100%;
				justify-content: center;
				display: flex;
				margin-top: 20rpx;

				.textContent {
					height: 54rpx;
					display: flex;
					align-items: center;

					.price {
						margin-left: 10rpx;
						line-height: 52.12rpx;
						font-size: 36rpx;
						font-weight: 700;
						color: rgba(212, 48, 48, 1);
					}
				}


				.submit {
					z-index: 9999999999;
					margin-right: 30rpx;
					display: flex;
					align-items: center;
					text-align: center;
					justify-content: center;
					width: 230rpx;
					height: 74rpx;
					opacity: 1;
					font-size: 28rpx;
					border-radius: 26rpx;
					color: rgba(255, 255, 255, 1);
					background: rgba(212, 48, 48, 1);
				}


			}

		}
	}
</style>